//
//  AppDelegate.m
//  B2C
//
//  Created by 李小龙 on 2017/7/17.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "AppDelegate.h"
#import "BaseTabbarViewController.h"
#import "LoginViewController.h"
#import "LaunchViewController.h"
#import <AlipaySDK/AlipaySDK.h>
#import "ShopcartOrderViewController.h"
#import "MineOrderViewController.h"
#import "OrderDetailViewController.h"
#import "OrderModel.h"
#import "MineRefundListViewController.h"
#import "RefundDetailViewController.h"
#import "PayStatusViewController.h"
#import "NotificationViewController.h"
#import "MessageModel.h"

// iOS10注册APNs所需头文件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate ()<WXApiDelegate,JPUSHRegisterDelegate,UNUserNotificationCenterDelegate>

@end

@implementation AppDelegate
- (instancetype)init {
    self = [super init];
    if (self) {
        [[UserInfo shareInstance] getUserModel];
    }
    return self;
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    // 设置tabbar
//    [self setRootViewController];
    [self setupTabbarVC];
    
    // 设置APNS
    [self setAPNS];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
    // 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
    [JPUSHService setupWithOption:launchOptions appKey:JPushAppKey
                          channel:@"AppStore"
                 apsForProduction:IsProduction];
    
//    NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
//    [defaultCenter addObserver:self selector:@selector(networkDidReceiveMessage:) name:kJPFNetworkDidReceiveMessageNotification object:nil];
    
    // 设置友盟 微信支付
    [self useUMengSocialData];
    
    // 更新用户信息
    [self getUserInterfaceModel];
    
    return YES;
}
- (void)networkDidReceiveMessage:(NSNotification *)notification {
//    NSDictionary * userInfo = [notification userInfo];
//    //    NSString *content = [userInfo valueForKey:@"content"];
//    NSDictionary *extras = [userInfo valueForKey:@"extras"];
//    //    NSString *customizeField1 = [extras valueForKey:@"customizeField1"]; //服务端传递的Extras附加字段，key是自己定义的
//    if ([self.window.rootViewController isKindOfClass:[BaseTabbarViewController class]]) {
//        UIViewController *vc = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
//        
//    }
}

- (void)setAPNS {
    //Required
    //notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = (JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound);
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加自定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}
#pragma mark - APNS
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma mark- JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        [ShowRedPoint shareInstance].isShowMessage = YES;
        [self receiveNotificationHandler:notification.request.content.userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
        
        [self notificationHandling:userInfo];
    }
    completionHandler();  // 系统要求执行这个方法
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    [self receiveNotificationHandler:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
    [self notificationHandling:userInfo];
}
#pragma mark -
- (void)getUserInterfaceModel {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if ([UserInfo shareInstance].isLogin) {
            [[UserInfo shareInstance] updateUserInterfaceModel:^(BOOL success) {
                [JPUSHService setAlias:[UserInfo shareInstance].user.mid completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                    NSLog(@"alias %@",iAlias);
                } seq:[UserInfo shareInstance].user.mid.integerValue];
            }];
        }
    });
}
- (void)setRootViewController {
    if ([[UserInfo shareInstance] isFirstLaunchApp]) {
        __weak typeof(self) weakSelf = self;
        LaunchViewController *guideVC = [[LaunchViewController alloc] init];
        guideVC.finish = ^() {
            [[UserInfo shareInstance] didLoadGuideView];
            [weakSelf setupTabbarVC];
        };
        self.window.rootViewController = guideVC;
    } else {
        [self setupTabbarVC];
    }
}
- (void)setupTabbarVC {
    
    BaseTabbarViewController *tabbar = [[BaseTabbarViewController alloc] init];
    self.window.rootViewController = tabbar;

    NSDictionary *dic = @{@"pageNumber":@"1",@"pageSize":PageSize};
    [MYAFNetworking POST:URL_Get_Shopcart parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *dics = responseObject;
            NSInteger totalCount = [dics[@"pagenation"][@"totalCount"] integerValue];
            [self updateBadgeValue:totalCount];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [self updateBadgeValue:0];
    }];
//
//    if ([UserInfo shareInstance].isLogin) {
//        BaseTabbarViewController *tabbar = [[BaseTabbarViewController alloc] init];
//        self.window.rootViewController = tabbar;
//        
//    } else {
//        LoginViewController *login = [[LoginViewController alloc] init];
//        UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:login];
//        self.window.rootViewController = nav;
//    }
}
- (void)updateBadgeValue:(NSInteger)totalCount {
    BaseTabbarViewController *tabbar = (BaseTabbarViewController *)self.window.rootViewController;
    UITabBarItem *item = [tabbar.tabBar.items objectAtIndex:2];
    if (totalCount > 0) {
        item.badgeValue = [NSString stringWithFormat:@"%ld",(long)totalCount];
    } else {
        item.badgeValue = nil;
    }
}
- (void)notificationHandling:(NSDictionary *)userInfo {
    //MARK:测试 有推送就显示，只有点击首页小信封图标才消除
    [ShowRedPoint shareInstance].isShowMessage = YES;
    
    UIViewController *vc = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
    if ([vc isKindOfClass:[HomeViewController class]]) {
        [vc viewWillAppear:NO];
    }
    
    //1发货，2退款，3商家修改订单价格，4系统消息
    switch ([[userInfo safeObjectForKey:@"itype"] integerValue]) {
        case 1:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.omid = [userInfo safeObjectForKey:@"omid"];
            OrderDetailViewController *orderDetailVC = [[OrderDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            orderDetailVC.fromType = FromTypeOther;
            [vc.navigationController pushViewController:orderDetailVC animated:YES];
        } break;
        case 2:
        {
            OrderModel *temp = [[OrderModel alloc] init];
            temp.omid = [userInfo safeObjectForKey:@"omid"];
            RefundDetailViewController *orderDetailVC = [[RefundDetailViewController alloc] init];
            orderDetailVC.detailModel = temp;
            [vc.navigationController pushViewController:orderDetailVC animated:YES];
        } break;
        case 3:
        {
            
        } break;
        case 4:
        {
            NotificationViewController *notificationVC = [[NotificationViewController alloc] init];
            MessageModel *model = [[MessageModel alloc] init];
            model.ititle = userInfo[@"title"];
            model.icontent = userInfo[@"content"];
            model.itype = userInfo[@"itype"];
            model.createtime = userInfo[@"createtime"];
            notificationVC.detailModel = model;
            [vc.navigationController pushViewController:notificationVC animated:YES];
        } break;
        default:
            break;
    }
}
- (void)receiveNotificationHandler:(NSDictionary *)userInfo {
    //MARK:测试 有推送就显示，只有点击首页小信封图标才消除
    [ShowRedPoint shareInstance].isShowMessage = YES;
    UIViewController *vc = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
    if ([vc isKindOfClass:[HomeViewController class]]) {
        [vc viewWillAppear:NO];
    }
    if ([vc isKindOfClass:[MineHomeViewController class]]) {
        [vc viewWillAppear:NO];
        return;
    }
    //1发货，2退款，3商家修改订单价格，4系统消息
    switch ([[userInfo safeObjectForKey:@"itype"] integerValue]) {
        case 1:
        {
            if ([vc isKindOfClass:[MineOrderViewController class]]) {
                [(MineOrderViewController *)vc getNetStatusData];
                [(MineOrderViewController *)vc getNetData];
            } else if ([vc isKindOfClass:[OrderDetailViewController class]]) {
                if ([((OrderDetailViewController *)vc).detailModel.omid isEqualToString:[userInfo safeObjectForKey:@"omid"]]) {
                    [(OrderDetailViewController *)vc getNetData];
                }
            }
        } break;
        case 2:
        {
            if ([vc isKindOfClass:[MineRefundListViewController class]]) {
                [(MineRefundListViewController *)vc getNetData];
            } else if ([vc isKindOfClass:[RefundDetailViewController class]]) {
                if ([((RefundDetailViewController *)vc).detailModel.omid isEqualToString:[userInfo safeObjectForKey:@"omid"]]) {
                    [(RefundDetailViewController *)vc getNetData];
                }
            }
        } break;
        case 3:
        {
            
        } break;
        case 4:
        {
            
        } break;
        default:
            break;
    }
}
#pragma mark - 友盟
- (void)useUMengSocialData {
    
    //打开日志
    [[UMSocialManager defaultManager] openLog:YES];
    
    /* 设置友盟appkey */
    [[UMSocialManager defaultManager] setUmSocialAppkey:UMeng_Key];//友盟的key
    
    // 获取友盟social版本号
    NSLog(@"UMeng social version: %@", [UMSocialGlobal umSocialSDKVersion]);
    
    //各平台的详细配置
    //设置分享到QQ互联的appId和appKey
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:UMeng_QQ_Key  appSecret:UMeng_QQ_Secret redirectURL:UMeng_RedirectURL];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Qzone appKey:UMeng_QQ_Key appSecret:UMeng_QQ_Secret redirectURL:UMeng_RedirectURL];
    
    //设置微信的appId和appKey
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:UMeng_Wechat_Key appSecret:UMeng_Wechat_Secret redirectURL:UMeng_RedirectURL];
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatTimeLine appKey:UMeng_Wechat_Key appSecret:UMeng_Wechat_Secret redirectURL:UMeng_RedirectURL];
    
    // 如果不想显示平台下的某些类型(微信收藏)，可用以下接口设置
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];
    
    // 设置微信支付
    [WXApi registerApp:UMeng_Wechat_Key];
}

/* RedPacket_FTR  */
//如果您使用了红包等融云的第三方扩展，请实现下面两个openURL方法
#if __IPHONE_OS_VERSION_MAX_ALLOWED > 100000
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey, id> *)options {
    // 其他如支付等SDK的回调
    if ([url.host isEqualToString:@"safepay"] || [url.host isEqualToString:@"platformapi"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            UIViewController *topVC = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
            NSString *omid;
            if ([topVC isKindOfClass:[ShopcartOrderViewController class]]) {
                omid = ((ShopcartOrderViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[OrderDetailViewController class]]) {
                omid = ((OrderDetailViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[MineOrderViewController class]]) {
                omid = ((MineOrderViewController *)topVC).omid;
            }
            if (TextIsNotNil(omid)) {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.omid = omid;
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    //MARK:成功
                    //                if (topVC.block) {
                    //                    topVC.block(YES);
                    //                }
                    //[topVC disMissSelf];
                    statusVC.type = StatusTypePaySuccess;
                } else {
                    //[MBProgressHUD myShowHUDAddedTo:topVC.view labelText:@"支付失败" animated:YES];
                    statusVC.type = StatusTypePayFail;
                }
                
                [topVC.navigationController pushViewController:statusVC animated:YES];
            }
        }];
    }
    
    if (![self handleUrl:url]) {
        
        return YES;
    }
    
    return NO;
}

#endif

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    // 其他如支付等SDK的回调
    if ([url.host isEqualToString:@"safepay"] || [url.host isEqualToString:@"platformapi"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            UIViewController *topVC = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
            NSString *omid;
            if ([topVC isKindOfClass:[ShopcartOrderViewController class]]) {
                omid = ((ShopcartOrderViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[OrderDetailViewController class]]) {
                omid = ((OrderDetailViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[MineOrderViewController class]]) {
                omid = ((MineOrderViewController *)topVC).omid;
            }
            if (TextIsNotNil(omid)) {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.omid = omid;
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    //MARK:成功
                    //                if (topVC.block) {
                    //                    topVC.block(YES);
                    //                }
                    //[topVC disMissSelf];
                    statusVC.type = StatusTypePaySuccess;
                } else {
                    //[MBProgressHUD myShowHUDAddedTo:topVC.view labelText:@"支付失败" animated:YES];
                    statusVC.type = StatusTypePayFail;
                }
                
                [topVC.navigationController pushViewController:statusVC animated:YES];
            }
        }];
    }
    
    if (![self handleUrl:url]) {
        
        return YES;
    }
    
    return NO;
}

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
    // 其他如支付等SDK的回调
    if ([url.host isEqualToString:@"safepay"] || [url.host isEqualToString:@"platformapi"]) {
        //跳转支付宝钱包进行支付，处理支付结果
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSLog(@"result = %@",resultDic);
            UIViewController *topVC = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
            NSString *omid;
            if ([topVC isKindOfClass:[ShopcartOrderViewController class]]) {
                omid = ((ShopcartOrderViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[OrderDetailViewController class]]) {
                omid = ((OrderDetailViewController *)topVC).omid;
            } else if ([topVC isKindOfClass:[MineOrderViewController class]]) {
                omid = ((MineOrderViewController *)topVC).omid;
            }
            if (TextIsNotNil(omid)) {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.omid = omid;
                if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
                    //MARK:成功
                    //                if (topVC.block) {
                    //                    topVC.block(YES);
                    //                }
                    //[topVC disMissSelf];
                    statusVC.type = StatusTypePaySuccess;
                } else {
                    //[MBProgressHUD myShowHUDAddedTo:topVC.view labelText:@"支付失败" animated:YES];
                    statusVC.type = StatusTypePayFail;
                }
                
                [topVC.navigationController pushViewController:statusVC animated:YES];
            }
        }];
    }
    
    if (![self handleUrl:url]) {
        
        return YES;
    }
    
    return NO;
}

- (BOOL)handleUrl:(NSURL *)url {
    //判断如果是支付的话  不走友盟方法  直接走微信和QQ的方法
    if([[url absoluteString] rangeOfString:[NSString stringWithFormat:@"%@://pay",UMeng_Wechat_Key]].location == 0)
        
        return [WXApi handleOpenURL:url delegate:self];
    
    else
        
        return [[UMSocialManager defaultManager] handleOpenURL:url];
    
}
//微信回调
-(void)onResp:(BaseResp*)resp {
    if ([resp isKindOfClass:[PayResp class]]){
        __weak typeof(UIViewController *) weakSelf = ((UINavigationController *)((BaseTabbarViewController *)self.window.rootViewController).selectedViewController).topViewController;
        NSString *omid;
        if ([weakSelf isKindOfClass:[ShopcartOrderViewController class]]) {
            omid = ((ShopcartOrderViewController *)weakSelf).omid;
        } else if ([weakSelf isKindOfClass:[OrderDetailViewController class]]) {
            omid = ((OrderDetailViewController *)weakSelf).omid;
        } else if ([weakSelf isKindOfClass:[MineOrderViewController class]]) {
            omid = ((MineOrderViewController *)weakSelf).omid;
        }
        if (TextIsNotNil(omid)) {
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.omid = omid;
            PayResp *response=(PayResp *)resp;
            switch(response.errCode){
                case WXSuccess:
                    //服务器端查询支付通知或查询API返回的结果再提示成功
                    NSLog(@"支付成功");
//                    if (((ShopcartOrderViewController *)weakSelf).block) {
//                        ((ShopcartOrderViewController *)weakSelf).block(YES);
//                    }
                    //[((ShopcartOrderViewController *)weakSelf) disMissSelf];
                    statusVC.type = StatusTypePaySuccess;
                    break;
                default:
                    //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"支付失败" animated:YES];
                    NSLog(@"支付失败，retcode=%d",resp.errCode);
                    statusVC.type = StatusTypePayFail;
                    break;
            }
            
            [weakSelf.navigationController pushViewController:statusVC animated:YES];
        }
    }
}
#pragma mark -
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [JPUSHService resetBadge];// 重置服务器 角标为0
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
